<template>
	<view class="container" :style="{ height: contentHeight + 'px' }">
		<scroll-view scroll-y="true" class="page-scroll" @scrolltolower="loadMore">
			<view class="tab-header">
				<view 
					class="tab-item" 
					v-for="(tab, index) in tabs" 
					:key="index"
					:class="{ active: activeTab === tab.value }"
					@click="switchTab(tab.value)"
				>
					{{tab.name}}
				</view>
			</view>
			
			<view class="filter-container">
				<view class="search-section">
					<input type="text" v-model="searchKeyword" placeholder="订单号/商品名称" @confirm="searchOrders" />
					<button class="search-btn" @click="searchOrders">搜索</button>
				</view>
			</view>
			
			<view class="order-list-container">
				<template v-if="orders.length > 0">
					<view class="order-item" v-for="(item, index) in orders" :key="index">
						<view class="order-header">
							<text class="order-number">订单号：{{item.orderNo}}</text>
							<text class="order-status" :class="'status-' + item.orderStatus">{{getStatusText(item.orderStatus)}}</text>
						</view>
						
						<view class="order-content">
							<view class="order-content-left">
								<view class="order-title">{{item.productTitle || item.productName}}</view>
								<view class="order-info">
									<text>下单时间：{{formatDate(item.createdAt)}}</text>
									<text>支付方式：{{getPaymentMethodText(item.paymentMethod)}}</text>
								</view>
							</view>
							<view class="order-price">¥{{item.orderAmount}}</view>
						</view>
						
						<view class="order-footer">
							<button 
								class="btn btn-cancel" 
								v-if="item.orderStatus === 0"
								@click="cancelOrder(item.orderId)"
							>取消订单</button>
							<button 
								class="btn btn-primary" 
								v-if="item.orderStatus === 0"
								@click="payOrder(item)"
							>立即支付</button>
							<button 
								class="btn btn-detail" 
								@click="viewOrderDetail(item)"
							>订单详情</button>
						</view>
					</view>
				</template>
				<view class="empty-tip" v-else>
					<image src="/static/empty-order.png" mode="aspectFit"></image>
					<text>暂无订单数据</text>
				</view>
				
				<view class="loading-more" v-if="isLoading">
					<text>加载中...</text>
				</view>
				
				<view class="no-more" v-if="!hasMore && orders.length > 0">
					<text>没有更多订单了</text>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import api from '../../api/api.js';
	
	export default {
		data() {
			return {
				activeTab: 'all',
				contentHeight: 0,
				tabs: [
					{ name: '全部', value: 'all' },
					{ name: '待支付', value: '0' },
					{ name: '已支付', value: '1' },
					{ name: '已取消', value: '2' },
					{ name: '已退款', value: '3' }
				],
				// 订单列表
				orders: [],
				// 搜索关键词
				searchKeyword: '',
				// 分页参数
				pageNum: 1,
				pageSize: 10,
				total: 0,
				hasMore: true,
				isLoading: false,
				// 查询参数
				queryParams: {
					orderStatus: ''
				}
			}
		},
		onLoad() {
			this.getSystemInfo();
			this.getOrders();
		},
		methods: {
			getSystemInfo() {
				const systemInfo = uni.getSystemInfoSync();
				const navHeight = systemInfo.statusBarHeight + 44;
				this.contentHeight = systemInfo.windowHeight - navHeight;
			},
			switchTab(tab) {
				this.activeTab = tab;
				this.resetPagination();
				
				// 设置订单状态过滤
				if (tab === 'all') {
					this.queryParams.orderStatus = '';
				} else {
					this.queryParams.orderStatus = tab;
				}
				
				this.getOrders();
			},
			// 获取订单列表
			async getOrders() {
				if (this.isLoading) return;
				
				this.isLoading = true;
				try {
					// 准备请求参数
					const params = {
						pageNum: this.pageNum,
						pageSize: this.pageSize,
						...this.queryParams
					};
					
					// 添加订单号搜索
					if (this.searchKeyword) {
						// 如果搜索关键词是纯数字且长度大于8，假设是订单号
						if (/^\d+$/.test(this.searchKeyword) && this.searchKeyword.length > 8) {
							params.orderNo = this.searchKeyword;
						} else {
							// 否则假设是商品名称，可以根据后端接口调整
							params.productName = this.searchKeyword;
						}
					}
					
					const res = await api.order.getMyOrders(params);
					
					if (res.code === 200) {
						if (this.pageNum === 1) {
							this.orders = res.rows || [];
						} else {
							this.orders = [...this.orders, ...(res.rows || [])];
						}
						
						// 处理订单数据，添加缺少的字段
						this.orders = this.orders.map(order => {
							return {
								...order,
								orderId: order.id,
								orderAmount: order.actualAmount,
								// 如果没有商品标题则显示"暂无商品信息"
								productName: order.productTitle || '暂无商品信息'
							};
						});
						
						this.total = res.total || 0;
						this.hasMore = this.orders.length < this.total;
					} else {
						uni.showToast({
							title: res.msg || '获取订单失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取订单列表失败', error);
					uni.showToast({
						title: '获取订单失败，请稍后重试',
						icon: 'none'
					});
				} finally {
					this.isLoading = false;
				}
			},
			// 加载更多
			loadMore() {
				if (this.hasMore && !this.isLoading) {
					this.pageNum++;
					this.getOrders();
				}
			},
			// 重置分页
			resetPagination() {
				this.pageNum = 1;
				this.total = 0;
				this.hasMore = true;
				this.orders = [];
			},
			// 搜索订单
			searchOrders() {
				this.resetPagination();
				this.getOrders();
			},
			// 获取订单状态文本
			getStatusText(status) {
				const statusMap = {
					'0': '待支付',
					'1': '已支付',
					'2': '已取消',
					'3': '已退款'
				}
				return statusMap[status] || '未知状态';
			},
			// 获取支付方式文本
			getPaymentMethodText(method) {
				const methodMap = {
					'1': '支付宝',
					'2': '微信',
					'3': '银行卡'
				}
				return methodMap[method] || '未支付';
			},
			// 格式化日期
			formatDate(dateStr) {
				if (!dateStr) return '';
				const date = new Date(dateStr);
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
			},
			// 支付订单
			async payOrder(item) {
				uni.showModal({
					title: '确认支付',
					content: `确定要支付订单 ${item.orderNo} 吗？`,
					success: async (res) => {
						if (res.confirm) {
							try {
								// 这里可以跳转到支付页面或直接调用支付接口
								const result = await api.order.payOrder(item.orderId, 2); // 默认微信支付
								
								if (result.code === 200) {
									uni.showToast({
										title: '支付成功',
										icon: 'success'
									});
									// 刷新订单列表
									this.resetPagination();
									this.getOrders();
								} else {
									uni.showToast({
										title: result.msg || '支付失败',
										icon: 'none'
									});
								}
							} catch (error) {
								console.error('支付订单失败', error);
								uni.showToast({
									title: '支付失败，请稍后重试',
									icon: 'none'
								});
							}
						}
					}
				});
			},
			// 取消订单
			async cancelOrder(orderId) {
				uni.showModal({
					title: '确认取消',
					content: '确定要取消该订单吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								const result = await api.order.cancelOrder(orderId);
								
								if (result.code === 200) {
									uni.showToast({
										title: '订单已取消',
										icon: 'success'
									});
									// 刷新订单列表
									this.resetPagination();
									this.getOrders();
								} else {
									uni.showToast({
										title: result.msg || '取消订单失败',
										icon: 'none'
									});
								}
							} catch (error) {
								console.error('取消订单失败', error);
								uni.showToast({
									title: '取消订单失败，请稍后重试',
									icon: 'none'
								});
							}
						}
					}
				});
			},
			// 查看订单详情
			viewOrderDetail(item) {
				uni.navigateTo({
					url: `/pages/detail/detail?id=${item.productId}`
				});
			}
		}
	}
</script>

<style lang="scss">
	.container {
		box-sizing: border-box;
		overflow: hidden;
		background-color: #f5f5f5;
		padding: 0;
	}
	
	.page-scroll {
		height: 100%;
		padding: 16rpx;
		box-sizing: border-box;
	}
	
	.tab-header {
		display: flex;
		background-color: #fff;
		margin-bottom: 16rpx;
		border-radius: 12rpx;
		height: 80rpx;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
	}
	
	.tab-item {
		flex: 1;
		text-align: center;
		padding: 0;
		font-size: 28rpx;
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.tab-item.active {
		color: #FF0000;
		font-weight: bold;
	}
	
	.tab-item.active:after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 25%;
		width: 50%;
		height: 4rpx;
		background-color: #FF0000;
	}
	
	.filter-container {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 16rpx;
		margin-bottom: 16rpx;
	}
	
	.search-section {
		display: flex;
	}
	
	.search-section input {
		flex: 1;
		height: 70rpx;
		background-color: #f5f5f5;
		border-radius: 35rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
	}
	
	.search-btn {
		margin-left: 16rpx;
		width: 120rpx;
		height: 70rpx;
		line-height: 70rpx;
		font-size: 28rpx;
		color: #fff;
		background-color: #FF0000;
		border-radius: 35rpx;
		padding: 0;
	}
	
	.order-list-container {
		width: 100%;
	}
	
	.order-item {
		background-color: #fff;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		padding: 20rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}
	
	.order-header {
		display: flex;
		justify-content: space-between;
		padding-bottom: 16rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}
	
	.order-number {
		font-size: 26rpx;
		color: #666;
	}
	
	.order-status {
		font-size: 26rpx;
		font-weight: bold;
	}
	
	.status-0 {
		color: #FF9500;
	}
	
	.status-1 {
		color: #34C759;
	}
	
	.status-2 {
		color: #8E8E93;
	}
	
	.status-3 {
		color: #007AFF;
	}
	
	.order-content {
		padding: 16rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.order-content-left {
		flex: 1;
	}
	
	.order-title {
		font-size: 30rpx;
		font-weight: bold;
		margin-bottom: 12rpx;
	}
	
	.order-info {
		font-size: 26rpx;
		color: #999;
		display: flex;
		flex-direction: column;
	}
	
	.order-info text {
		margin-bottom: 6rpx;
	}
	
	.order-price {
		font-size: 36rpx;
		font-weight: bold;
		color: #FF0000;
		margin-left: 20rpx;
	}
	
	.order-footer {
		padding-top: 16rpx;
		display: flex;
		justify-content: flex-end;
	}
	
	.btn {
		font-size: 26rpx;
		padding: 8rpx 24rpx;
		border-radius: 30rpx;
		line-height: 1.5;
		margin: 0 0 0 16rpx;
	}
	
	.btn-primary {
		color: #fff;
		background-color: #FF0000;
	}
	
	.btn-cancel {
		color: #666;
		background-color: #f5f5f5;
		border: 1rpx solid #ddd;
	}
	
	.btn-detail {
		color: #666;
		background-color: #fff;
		border: 1rpx solid #ddd;
	}
	
	.empty-tip {
		padding: 100rpx 0;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		color: #999;
		font-size: 28rpx;
	}
	
	.empty-tip image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 20rpx;
	}
	
	.loading-more, .no-more {
		text-align: center;
		padding: 20rpx 0;
		color: #999;
		font-size: 26rpx;
	}
</style> 